<template>
  <div class="app-container">
    <div class="left-container">
      <el-tree
        ref="tree"
        v-model="leftId"
        :data="leftData"
        node-key="id"
        default-expand-all="true"
        highlight-current="true"
        :props="leftTreeProps"
        expand-on-click-node="false"
        @current-change="handleCateChange"
      >
        <span slot-scope="{ node, data }" class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>
            <el-button
              type="text"
              size="mini"
              @click="() => handleUpdateCate(data)"
            >
              <i class="el-icon-edit" />
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="() => handleRemoveCate(data)"
            >
              <i class="el-icon-delete" />
            </el-button>
          </span>
        </span>
      </el-tree>
    </div>
    <div class="content-container">
      <div class="filter-container">
        <el-input v-model="listQuery.key" placeholder="角色名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          查询
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
          新增
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreateCate">
          新增分类
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-edit" @click="handleMultiDelete">
          批量删除
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleEnable">
          批量启用
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-edit" @click="handleDisable">
          批量禁用
        </el-button>
      </div>

      <el-table
        :data="tableData"
        style="width: 100%;margin-bottom: 20px;"
        row-key="id"
        border
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        @selection-change="tableSelected"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          prop="name"
          label="字典名称"
          sortable
          width="380"
        />
        <el-table-column
          prop="seq"
          width="100"
          label="显示顺序"
        />
        <el-table-column
          prop="status"
          width="120"
          label="状态"
        >
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.status==true"
              size="mini"
              @click="handleEditStatus(scope.$index, scope.row,0)"
            >启用</el-button>
            <el-button
              v-if="scope.row.status==false"
              size="mini"
              type="danger"
              @click="handleEditStatus(scope.$index, scope.row,1)"
            >禁用</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="300">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="分类" prop="categoryId">
          <el-tree
            ref="tree"
            v-model="temp.categoryId"
            :data="leftData"
            show-checkbox
            node-key="id"
            check-strictly="true"
            :props="leftTreeProps"
            @check-change="cateTreeCheck"
          />
        </el-form-item>
        <el-form-item label="上级" prop="pid">
          <el-tree
            ref="tree1"
            v-model="temp.pid"
            :data="dicParentData"
            show-checkbox
            node-key="id"
            :check-strictly="true"
            :default-expand-all="false"
            :props="leftTreeProps"
            @check-change="treeCheck"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="key" prop="key">
          <el-input v-model="temp.key" />
        </el-form-item>
        <el-form-item label="value" prop="value">
          <el-input v-model="temp.value" type="textarea" autosize="true" />
        </el-form-item>
        <el-form-item label="说明" prop="remark">
          <el-input v-model="temp.remark" type="textarea" autosize="true" />
        </el-form-item>
        <el-form-item label="排序" prop="seq">
          <el-col :span="8">
            <el-input v-model="temp.seq" type="number" />
          </el-col>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="temp.status"
            active-text="启用"
            inactive-text="禁用"
            active-value="true"
            inactive-value="false"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormCateVisible" width="300">
      <el-form ref="dataForm" :rules="rules" :model="tempCate" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="上级" prop="pid">
          <el-tree
            ref="tree"
            v-model="tempCate.pid"
            :data="leftData"
            show-checkbox
            node-key="id"
            check-strictly="true"
            :props="leftTreeProps"
            @check-change="cateTreeCheck"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="tempCate.name" />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="tempCate.code" />
        </el-form-item>
        <el-form-item label="排序" prop="seq">
          <el-col :span="8">
            <el-input v-model="tempCate.seq" type="number" />
          </el-col>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="tempCate.status"
            active-text="启用"
            inactive-text="禁用"
            active-value="true"
            inactive-value="false"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormCateVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createCateData():updateCateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { categoryTree, createCate, updateCate, deleteCate, tree, create, update, remove, getByCateCode } from '@/api/dictionary'
import waves from '@/directive/waves' // waves directive

export default {
  directives: { waves },
  data() {
    return {
      listQuery: {
        index: 1,
        size: 15,
        key: '',
        categoryId: 0
      },
      tableData: [],
      leftData: [],
      dicParentData: [],
      leftTreeProps: { label: 'name' },
      listLoading: false,
      leftId: 0,
      dialogFormCateVisible: false,
      dialogFormVisible: false,
      textMap: {
        update: '编辑',
        create: '新建'
      },
      dialogStatus: '',
      tempCate: {
        id: 0,
        name: '',
        pid: 0,
        status: true,
        seq: 0,
        code: ''
      },
      temp: {
        id: 0,
        name: '',
        pid: 0,
        status: true,
        seq: 0,
        categoryId: 0,
        key: '',
        value: '',
        remark: ''
      },
      tableSelectedKeys: []
    }
  },
  created() {
    this.getCategoryData()
    this.getDicData()
  },
  methods: {
    getDicData() {
      tree(this.listQuery).then(response => {
        this.tableData = response.data.data
        if (this.listQuery.categoryId === 0) {
          this.dicParentData = response.data.data
        }
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getCategoryData() {
      categoryTree().then(response => {
        this.leftData = response.data.data
        // this.userDepartData = response.data.data
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleCreate() {
      this.dialogFormVisible = true
      this.dialogStatus = 'create'
      this.resetTemp()
    },
    handleCreateCate() {
      this.dialogFormCateVisible = true
      this.dialogStatus = 'create'
      this.resetCateTemp()
    },
    createCateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.tempCate)
          createCate(tempData).then(res => {
            const response = res.data
            if (response.success) {
              this.getCategoryData()
              this.dialogFormCateVisible = false
            } else {
              this.$message({
                message: response.msg,
                type: 'failed'
              })
            }
          })
        }
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          create(this.temp).then(res => {
            const response = res.data
            if (response.success) {
              this.getDicData()
              this.dialogFormVisible = false
            } else {
              this.$message({
                message: response.msg,
                type: 'failed'
              })
            }
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          update(this.temp).then(res => {
            const response = res.data
            if (response.success) {
              this.getDicData()
              this.dialogFormVisible = false
            } else {
              this.$message({
                message: response.msg,
                type: 'failed'
              })
            }
          })
        }
      })
    },
    handleEdit(index, row) {
      this.dialogFormVisible = true
      this.dialogStatus = 'update'
      this.temp = row
      this.$refs.tree.setCheckedKeys([row.categoryId])
      this.$refs.tree1.setCheckedKeys([row.pid])
    },
    handleUpdateCate(node, data) {
      this.dialogFormCateVisible = true
      this.dialogStatus = 'update'
      // const parent = node.parent;
      // const children = parent.data.children || parent.data;
      // const index = children.findIndex(d => d.id === data.id);
      // children.splice(index, 1);
      this.tempCate = node
      this.$refs.tree.setCheckedKeys([node.pid])
    },
    updateCateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.tempCate)
          updateCate(tempData).then(res => {
            const response = res.data
            if (response.success) {
              this.getCategoryData()
              this.dialogFormCateVisible = false
            } else {
              this.$message({
                message: response.msg,
                type: 'failed'
              })
            }
          })
        }
      })
    },
    handleRemoveCate(node, data) {
      if (node.children.length > 0) {
        this.$alert('存在下级，不能删除哦。', '提示', {
          confirmButtonText: '确定',
          type: 'warning',
          center: true
        })
        return false
      }
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        deleteCate([node.id]).then(res => {
          const response = res.data
          if (response.success) {
            this.getCategoryData()
          } else {
            this.$message({
              message: response.msg,
              type: 'failed'
            })
          }
        })
      })
    },
    removeData(preDelDicIds) {
      this.$confirm('此操作将永久删除字典, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        remove(preDelDicIds).then(res => {
          const response = res.data
          if (response.success) {
            this.getDicData()
          } else {
            this.$message({
              message: response.msg,
              type: 'failed'
            })
          }
        })
      })
    },
    cateTreeCheck(data, checked, node) {
      if (checked) {
        this.$refs.tree.setCheckedNodes([data])
        this.tempCate.pid = this.$refs.tree.getCheckedKeys()[0]
        this.temp.categoryId = this.$refs.tree.getCheckedKeys()[0]
      }
    },
    treeCheck(data, checked, node) {
      if (checked) {
        this.$refs.tree1.setCheckedNodes([data])
        this.temp.pid = this.$refs.tree1.getCheckedKeys()[0]
      }
    },
    resetTemp() {
      this.temp = {
        id: 0,
        name: '',
        pid: 0,
        status: true,
        seq: 0,
        key: '',
        value: '',
        remark: ''
      }
      this.$refs.tree1.setCheckedNodes([0])
    },
    resetCateTemp() {
      this.tempCate = {
        id: 0,
        name: '',
        pid: 0,
        status: true,
        seq: 0,
        code: ''
      }
    },
    handleFilter() {
      this.getDicData()
    },
    handleCateChange(data, node) {
      this.listQuery.categoryId = data.id
      this.getDicData()
    },
    handleEditStatus(index, row) {

    },
    handleEnable() {

    },
    handleDisable() {

    },
    handleMultiDelete() {
      if (this.tableSelectedKeys.length > 0) {
        this.removeData(this.tableSelectedKeys)
      } else {
        this.$message({
          message: '请选择要删除的数据。',
          type: 'warn'
        })
      }
    },
    handleDelete(index, row) {
      this.removeData([row.id])
    },
    tableSelected(selectedData) {
      this.tableSelectedKeys = []
      selectedData.forEach(a => {
        this.tableSelectedKeys.push(a.id)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .left-container {
    float: left;
    width: 15%;
    border: #ccc solid 1px;
    padding: 5px;
    min-height: 800px;
    overflow: auto;
  }
  .content-container {
    float: left;
    width: 84%;
    margin-left: 10px;
  }
}
</style>
